package com.e3.web.widget.client;

import java.util.ArrayList;
import java.util.List;

import com.e3.web.widget.model.MyTreeModel;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;


public class MyTreePanel<M extends MyTreeModel> extends TreePanel<M> {

	public MyTreePanel(TreeStore<M> store) {
		super(store);
	}
	
	public MyTreePanel<M>.TreeNode getSelectedTreeNode(M m){
		return findNode(m);
	}
	
	public void updateTreeModel(M model,boolean isExpand){
		getStore().update(model);
		updateTreeNodeModel(model,isExpand);
	}
	
	public void updateTreeNodeModel(M model,boolean isExpand){
		TreePanel<M>.TreeNode treeNode = getSelectedTreeNode(model);
		if(treeNode == null){
			@SuppressWarnings("unchecked")
			M pModel = (M)model.getParentModel();
			if(pModel == null){
				pModel = getStore().getRootItems().get(0);
			}
			M pNodeModel = getSelectedTreeNode(pModel).getModel();
			if(pNodeModel!=null){
				pNodeModel.setHasChildren(true);
				getStore().add(pNodeModel, model, true);
				setExpanded(model, true);
			}
		}
		else{
			M treeNodeModel = treeNode.getModel();
			if(treeNodeModel!=null){
				String[] fNames = model.getModelFields();
				for(int i=0;i<fNames.length;i++){
					String key = fNames[i];
					treeNodeModel.set(key, model.get(key));
				}
				setExpanded(treeNodeModel, true);
			}
		}
	}
	
	public void removeTreeNodes(List<M> models){
		if(models == null || models.isEmpty()){
			return;
		}
		List<M> pModels = new ArrayList<M>(models.size());
		for (M model : models) {
			getStore().remove(model);
			if(pModels.contains(model)){
				pModels.remove(model);
			}
			M pModel = (M)model.getParentModel();
			if(!pModels.contains(pModel)){
				pModels.add(pModel);
			}
		}
		List<M> selections = new ArrayList<M>(1);
		if(pModels.isEmpty()){
			selections.add(getStore().getRootItems().get(0));
		}
		else{
			selections.add(pModels.get(0));
		}
		getSelectionModel().setSelection(selections);	
	}

}
